import 'dart:async';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:kwai/kwai_platform_interface.dart';
import 'package:kwai/model/callback_result.dart';

class MethodChannelKwai extends KwaiPlatform {
  final StreamController<CallbackResult> _streamController =
      StreamController.broadcast();

  @visibleForTesting
  late final methodChannel = const MethodChannel('kwai')
    ..setMethodCallHandler((call) {
      return _handleMethod(call);
    });

  _handleMethod(MethodCall call) {
    final json =
        (call.arguments as Map<dynamic, dynamic>).cast<String, dynamic>();
    switch (call.method) {
      case "callback":
        _streamController.add(CallbackResult.fromJson(json));
        break;
    }
  }

  @override
  Future<String> registerKwaiApp({
    String? apiKey,
    String? universalLink,
  }) async {
    final arguments =
        Platform.isIOS ? {"apiKey": apiKey, "link": universalLink} : null;
    final initState =
        await methodChannel.invokeMethod<String>("init", arguments);
    return initState ?? '';
  }

  @override
  Future<String> authorLogin({String? scope}) async {
    final arguments = {"scope": scope};
    final state =
        await methodChannel.invokeMethod<String>("authorLogin", arguments);
    return state ?? '';
  }

  @override
  Stream<CallbackResult> authorLoginCallback() {
    return _streamController.stream;
  }
}
